package cn.ddm.hrm.exception;


import cn.ddm.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //可以在controller执行前，后做一些事情
public class GlobalExceptionHandler {

    //处理全局异常 GlobalException处理哪个异常，返回AjaxResult
    @ExceptionHandler(GlobalException.class)//处理GlobalException
    public AjaxResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me()
                .setSuccess(false)
                .setCode(e.getCode())
                .setMessage(e.getMessage());
    }

    //处理参数校验异常 JSR303
    @ExceptionHandler(MethodArgumentNotValidException.class)//处理GlobalException
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        fieldErrors.forEach(error->{
           String field= error.getField();
            String message = error.getDefaultMessage();
            sb.append(field).append(message).append(",");
        });
        return AjaxResult.me()
                .setSuccess(false)
                .setCode(ErrorCode.CODE_400_PARAM_VALID.getCode())
                .setMessage(sb.toString());
    }
    //处理系统异常 Exception
    @ExceptionHandler(Exception.class)//处理GlobalException
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        //权限异常处理 AccessDeniedException
        if (e.getClass().getName().contains("AccessDeniedException")){
            return AjaxResult.me()
                    .setSuccess(false)
                    .setCode(ErrorCode.CODE_403_SYSTEM_ERROR.getCode())
                    .setMessage(ErrorCode.CODE_403_SYSTEM_ERROR.getMessage());
        }
        return AjaxResult.me()
                .setSuccess(false)
                .setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode())
                .setMessage(ErrorCode.CODE_500_SYSTEM_ERROR.getMessage());
    }
}
